import {
  Component,
  OnInit,
  Input,
  ViewEncapsulation,
  ViewChild,
  ElementRef,
  ChangeDetectorRef,
  OnDestroy,
  AfterViewInit,
  ChangeDetectionStrategy,
  Output,
  EventEmitter
} from '@angular/core';

import {Router} from '@angular/router';

@Component({
  selector: 'seed-cycle',
  templateUrl: './cycle.component.html',
  styleUrls: ['./cycle.component.scss'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CycleComponent implements AfterViewInit, OnDestroy {
  @Input() slides;
  @Output() clicked: EventEmitter<any> = new EventEmitter<any>();
  timer: any;
  index = 0;

  @ViewChild('wrapper') wrapper: ElementRef;

  constructor(public cdRef: ChangeDetectorRef,
              public router: Router) {

  }

  /**
   * 前往轮播详情
   * @param slide 轮播对象
   */
  goToTarget(slide: any) {
    this.clicked.emit(slide);
  }

  /**
   * 自动轮播
   */
  autoPlay() {
    const that = this;
    this.timer = setInterval(() => {
      if (Array.isArray(that.slides) && that.slides.length > 1) {
        that.nextSlider();
      } else {
        clearInterval(this.timer);
      }
    }, 3000);

  }

  /**
   * 滑動處理
   * @param type 手勢類型
   */
  handleSwipe(type: string) {
    if (this.slides.length > 1) {
      clearInterval(this.timer); // stop auto play
      switch (type) {
        case 'swipeleft':
          this.nextSlider();
          break;
        case 'swiperight':
          this.prevSlider();
          break;
        default:
          return;
      }
      this.autoPlay(); // restart auto play
    }
  }

  /**
   * 上一张
   */
  prevSlider() {
    let currentSliderIndex = this.index;
    if (currentSliderIndex === 0) {
      currentSliderIndex = this.slides.length - 1;
    } else {
      currentSliderIndex -= 1;
    }
    this.slideTo(currentSliderIndex);
  }

  /**
   * 下一张
   */
  nextSlider() {
    let currentSliderIndex = this.index;
    if (currentSliderIndex >= this.slides.length - 1) {
      currentSliderIndex = 0;
    } else {
      currentSliderIndex += 1;
    }
    this.slideTo(currentSliderIndex);
  }

  /**
   * 滑动至目標滑塊
   * @param index 滑块索引
   */
  slideTo(index: number) {
    this.index = index;
    this.wrapper.nativeElement.style.marginLeft = `-${100 * index}%`;
    this.cdRef.detectChanges();
  }

  /**
   * 点击滑动
   * @param index 滑块索引
   */
  clickSlide(index: number) {
    clearInterval(this.timer); // stop auto play
    this.slideTo(index);
    this.autoPlay(); // restart auto play
  }

  ngAfterViewInit() {
    this.autoPlay();
  }

  ngOnDestroy() {
    clearInterval(this.timer);
  }
}
